package org.shan.lis.utils;

import java.nio.ByteBuffer;

public class ByteBuffUtils {

    public static ByteBuffer initBuffer(int capacity){
        ByteBuffer buffer = ByteBuffer.allocate(capacity);
        buffer.flip();

        return buffer;
    }

    public static synchronized void addBytes(ByteBuffer packetBuff, byte[] addBytes) {


        if (addBytes != null) {

//            LogUtils.d(String.format("addBytes before pos=%d, limit=%d", packetBuff.position(),
//                    packetBuff.limit()));
            packetBuff.compact();

//            LogUtils.d(String.format("addBytes after pos=%d, limit=%d", packetBuff.position(),
//                    packetBuff.limit()));

            int len = addBytes.length;
            if (len > packetBuff.remaining()) {
                packetBuff.clear();
                System.err.println(String.format("Buffer is Overflow remaining:%d  addlen:%d ",
                        packetBuff.remaining(), len));
            }
            packetBuff.put(addBytes, 0, len);
            packetBuff.flip();
        }
    }

    public static synchronized void addBytes(ByteBuffer packetBuff, byte[] addBytes, int len) {
        if (addBytes != null) {
            packetBuff.compact();

            if (len > packetBuff.remaining()) {
                packetBuff.clear();
                System.err.println(String.format("Buffer is Overflow remaining:%d  addlen:%d ",
                        packetBuff.remaining(), len));
            }
            packetBuff.put(addBytes, 0, len);
            packetBuff.flip();
        }
    }

    public static synchronized int getSize(ByteBuffer packetBuff) {
        return packetBuff.remaining();
    }

    public static synchronized byte[] getBytes(ByteBuffer packetBuff, int size) {
        byte[] bs = null;
        if (packetBuff.remaining() >= size) {
            bs = new byte[size];
            packetBuff.get(bs);
        }
        return bs;
    }

    public static synchronized byte getByte(ByteBuffer packetBuff) {
        byte[] bytes = getBytes(packetBuff, 1);
        if (bytes != null && bytes.length > 0){
            return bytes[0];
        }else{
            throw new RuntimeException("buff is empty");
        }
    }

    public static boolean compare(byte[] b1, int len1, byte[] b2, int len2){
        if (len1 == len2){
            for (int i = 0; i < len1; i++) {
                if (b1[i] != b2[i]){
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffUtils.initBuffer(5);

        ByteBuffUtils.addBytes(buffer, new byte[6]);
    }
}
